<?php

namespace Apps\Pay\Controllers;

use Apps\Common\Enum\PayState;
use Apps\Common\Enum\PayType;
use WeiXin\Pay;

class WeixinController extends BaseController
{
    private $weixinConfig;
    public function initialize()
    {
        $this->view->disable();
        $payConfig = include APP_COMMON_PATH . "base-config/pay.php";
        $this->weixinConfig = $payConfig['weixin'];
    }

    public function notifyAction()
    {
        $req = $this->request;
        $body = $req->getRawBody();
        $pay = new Pay($this->weixinConfig);
        $checkResult = $pay->notifyVerify($body);
        $echoResult = function($success, $msg='OK'){
            $result = $success ? 'SUCCESS' : 'FAIL';
            echo "<xml><return_code><![CDATA[$result]]></return_code><return_msg><![CDATA[$msg]]></return_msg></xml>";
        };
        if(is_int($checkResult)) {
        // 错误处理,
        // 100-xml解析异常，101-签名验证失败，102-返回状态码错误，103-业务结果异常
            switch($checkResult) {
                case PayState::ASYNC_FAIL_XML:
                    $echoResult(false, 'xml error');
                    break;
                case PayState::ASYNC_FAIL_SIGN:
                    $echoResult(false, 'sign verify error');
                    break;
                case PayState::ASYNC_FAIL_RETURN_CODE:
                    $echoResult(true);
                    break;
                case PayState::ASYNC_FAIL_RESULT_CODE:
                    $echoResult(true);
                    break;
            }
            $this->savePayLog(0, 0, PayType::WEIXIN, $checkResult, $body);
            return;
        }
        $appId = $checkResult['appid'];
        $mchId = $checkResult['mch_id'];
        $resultCode = $checkResult['result_code'];
        $openId = $checkResult['openid'];
        $totalFee = $checkResult['total_fee']; //总金额，单位为分
        $cashFee = $checkResult['cash_fee']; //现金支付金额
        $transactionId = $checkResult['transaction_id']; //微信支付订单号
        $outTradeNoStr = $checkResult['out_trade_no']; //商户订单号

        // 拆分订单号
        $outTradeNoArr = explode('-', $outTradeNoStr);
        $outTradeNo = $outTradeNoArr[0];

        $this->payHandle($echoResult, PayType::WEIXIN, $transactionId, $outTradeNo, $totalFee, $body);    }
}